package com.gan.bi.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author gbw
 * @date 2023/7/18
 */
@RestController
@RequestMapping("/queue")
@Slf4j
@Profile({"dev","local"})
public class QueueController {

    @Resource
    ThreadPoolExecutor threadPoolExecutor;

    /**
     * 执行任务
     * @param name
     */
    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(() -> {
            System.out.println("任务执行中:" + name + "  执行人:" + Thread.currentThread().getName());
            try {
                Thread.sleep(600000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },threadPoolExecutor);
    }


    /**
     * 查看线程情况
     */
    @GetMapping("/get")
    public String get(){
        HashMap<String, Object> res = new HashMap<>();
        int size = threadPoolExecutor.getQueue().size();
        res.put("队列长度/任务个数",size);
        long taskCount = threadPoolExecutor.getTaskCount();
        res.put("任务数量",taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        res.put("已完成任务数量",completedTaskCount);
        long activeCount = threadPoolExecutor.getActiveCount();
        res.put("正在工作的线程数",activeCount);
        return JSONUtil.toJsonStr(res);
    }


}
